/*
 * Copyright © 2004-2014 chenYuan. All rights reserved.
 * @Website:wwww.jspx.net
 * @Mail:39793751@qq.com
 * @author: chenYuan , 陈原
 * @License: Jspx.net Framework Code is open source (LGPL)，Jspx.net Framework 使用LGPL 开源授权协议发布。
 * @jvm:jdk1.6+  x86/amd64
 *
 */
package com.jspx.scriptmark.core.dispose;

import com.jspx.scriptmark.Phrase;
import com.jspx.scriptmark.core.TagNode;
import com.jspx.scriptmark.core.EnvRunner;
import com.jspx.scriptmark.core.block.TryBlock;
import com.jspx.scriptmark.exception.ScriptRunException;
import java.io.Writer;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: chenYuan
 * Date: 2009-1-2
 * Time: 16:24:35
 */
public class TryPhrase implements Phrase {
    public TryPhrase() {

    }

    public int getRun(EnvRunner env, TagNode tagNode, Writer out) throws Exception {
        TryBlock tryBlock = (TryBlock) tagNode;
        int bc = 0;
        try {
            List<TagNode> tryList = tryBlock.getBodyList();
            for (TagNode node : tryList) {
                try {
                    env.runBlock(node, out);
                } catch (Exception e) {
                    throw new ScriptRunException(node, tagNode.getTagName());
                }
            }
            tryList.clear();
        } catch (Exception e) {
            List<TagNode> catchList = tryBlock.getCatchBodyList();
            for (TagNode node : catchList) {
                try {
                    bc = env.runBlock(node, out);
                } catch (Exception ex) {
                    throw new ScriptRunException(node, tagNode.getTagName());
                }
                if (bc != 0) return bc;
            }
            catchList.clear();
        } finally {
            List<TagNode> finList = tryBlock.getFinallyBodyList();
            for (TagNode node : finList) {
                try {
                    bc = env.runBlock(node, out);
                } catch (Exception ex) {
                    throw new ScriptRunException(node, tagNode.getTagName());
                }
                if (bc != 0) break;
            }
            finList.clear();
        }
        return bc;
    }
}